package com.nxn.core.service.impl;

import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;

import com.googlecode.ehcache.annotations.Cacheable;
import com.nxn.core.service.DataLoaderService;
import com.nxn.core.web.tag.Bundles;
import com.nxn.core.web.tag.Group;
import com.nxn.core.web.tag.Releases;

@Service("dataLoaderService")
public class DataLoaderServiceImpl implements DataLoaderService {

	private static InputStream getInputStream(String xmlFilePath) {
		return DataLoaderServiceImpl.class.getResourceAsStream(xmlFilePath);
	}
	
	/**
     * 获取指定xml文档的Document对象,xml文件必须在classpath中可以找到
     *
     * @param xmlFilePath xml文件路径
     * @return Document对象
     */
    private static Document parse2Document(String xmlFilePath) {
       
    	SAXReader reader = new SAXReader();
        Document document = null;
        try {
            InputStream in = getInputStream(xmlFilePath);
            document = reader.read(in);
        } catch (DocumentException e) {
            System.out.println(e.getMessage());
            System.out.println("读取classpath下xmlFileName文件发生异常，请检查CLASSPATH和文件名是否存在！");
            e.printStackTrace();
        }
        return document;
    }
	
    @Override
    @Cacheable(cacheName = "demoCache")
    public Group initWebAssets(String xmlFileName) {
    	 System.err.println("init the web asset ...");
    	
    	//将XML文档转换为Document的对象
        Document document = parse2Document(xmlFileName);
        
        Node version = document.selectSingleNode("/root/config/version");
        Element asset = document.elementByID(version.getText());
        
        Bundles bundles = new Bundles();
        
        List<Element> jsElems = asset.selectNodes("bundles/javaScripts/javaScript");
        for (Iterator<Element> iterator = jsElems.iterator(); iterator.hasNext();) {
			Element jsElem = iterator.next();
			bundles.addJavaScript("script/" + version.getText() + "/" + jsElem.attributeValue("src"));
		}
    	
    	List<Element> cssElems = asset.selectNodes("bundles/styleSheets/styleSheet");
    	for (Iterator<Element> iterator = cssElems.iterator(); iterator.hasNext();) {
			Element cssElem = iterator.next();
			bundles.addStyleSheet("script/" + version.getText() + "/" + cssElem.attributeValue("href"));
		}
    	
    	return new Group(bundles, new Releases());
    }

}
